//
//  PPOtherPetTableViewController.m
//  pet
//
//  Created by 陈无忌 on 10/13/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPPetDetailTableViewController.h"
#import "PPEditPetInfoTableViewController.h"
#import "PPPreviewPetPhotoViewController.h"
#import "PPPetPhotoCollectionViewCell.h"
#import "supportingHeadFiles.h"
#import "PPSystemConfiguraton.h"

@interface PPPetDetailTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *petAvatarImageView;
@property (weak, nonatomic) IBOutlet UILabel *petNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *petAgeLabel;
@property (weak, nonatomic) IBOutlet UILabel *petBreedLabel;
@property (weak, nonatomic) IBOutlet UILabel *petBreedingLabel;
@property (weak, nonatomic) IBOutlet UIImageView *petSexImageView;

@property (weak, nonatomic) IBOutlet UILabel *introductionLabel;
@property (weak, nonatomic) IBOutlet UILabel *lenthLabel;
@property (weak, nonatomic) IBOutlet UILabel *weightLabel;
@property (weak, nonatomic) IBOutlet UILabel *colorLabel;
//@property (weak, nonatomic) IBOutlet UILabel *favorCountLabel;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *editButton;

@property (weak, nonatomic) IBOutlet UILabel *photoLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *petPhotoCollectionView;
@property (nonatomic) int introductionHeight;
@property (nonatomic) int photoCellHeight;
@property (weak, nonatomic) IBOutlet UIView *deleteView;

@end

@implementation PPPetDetailTableViewController

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.introductionHeight = 0;
    self.photoCellHeight = 0;
    self.petPhotoCollectionView.delegate = self;
    self.petPhotoCollectionView.dataSource = self;
    
    if (self.pet.userId == [PPSystemConfiguraton sharedSystemConfiguration].userInfo.id) {
        self.editButton.title = @"编辑";
    }else{
        self.editButton.title = @"";
    }
    [self petDataInit];
    //接收到宠物信息更新的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getPet) name:@"refreshPetInfo" object:nil];
    
    
    if ([PPSystemConfiguraton sharedSystemConfiguration].userInfo.id == self.pet.userId) {
        self.deleteView.hidden = NO;
    }else{
        self.deleteView.hidden = YES;
    }
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)getPet
{
    NSString *url = [PPAPIList getAPIList].PPQueryPetById;
    NSDictionary *params = @{@"petId":@(self.pet.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *err = nil;
        NSDictionary *resultMap = responseObject[@"resultMap"];
        NSDictionary *petDic = resultMap[@"pet"];
        self.pet = [[PPPetInfo alloc] initWithDictionary:petDic error:&err];
        [self petDataInit];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

-(void)petDataInit
{
    [self.petAvatarImageView setImageWithURL:[PPImageUrl getImageUrl:self.pet.petAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    self.petNameLabel.text = self.pet.petName;
    if (self.pet.birth) {
        self.petAgeLabel.text = self.pet.birth;
    }else{
        self.petAgeLabel.text = @"未设置";
    }
    
    self.petBreedLabel.text = self.pet.petBreed;
    if ([self.pet.breeding isEqualToString:@"yes"]) {
        self.petBreedingLabel.text = @"需要";
        self.photoLabel.hidden = NO;
        self.petPhotoCollectionView.hidden = NO;
        self.photoCellHeight = 70;
    }else{
        self.petBreedingLabel.text = @"不需要";
        self.photoLabel.hidden = YES;
        self.petPhotoCollectionView.hidden = YES;
        self.photoCellHeight = 0;
    }
    switch (self.pet.petGender) {
        case 0:
            [self.petSexImageView setImage:[UIImage imageNamed:@"maleBig"]];
            break;
        case 1:
            [self.petSexImageView setImage:[UIImage imageNamed:@"femaleBig"]];
            break;
        default:
            break;
    }
    self.introductionLabel.frame = CGRectMake(10, 36, 297, 15);
    self.introductionLabel.numberOfLines = 0;
    self.introductionLabel.lineBreakMode = NSLineBreakByCharWrapping;
    if (self.pet.introduction.length > 0) {
        self.introductionLabel.text = self.pet.introduction;
    }else{
        self.introductionLabel.text = @"主人很懒，什么都没有写...";
    }
    [self.introductionLabel sizeToFit];
    self.introductionHeight = 36 + self.introductionLabel.frame.size.height  + 10;
    
    if (self.pet.petLong) {
        self.lenthLabel.text = [NSString stringWithFormat:@"%.2f",self.pet.petLong];
    }else{
        self.lenthLabel.text = @"未设置";
    }
    if (self.pet.weight) {
        self.weightLabel.text = [NSString stringWithFormat:@"%.2f",self.pet.weight];
    }else{
        self.weightLabel.text = @"未设置";
    }
    if (self.pet.color && self.pet.color.length > 0) {
        self.colorLabel.text = self.pet.color;
    }else{
        self.colorLabel.text = @"未设置";
    }
    
    [self.tableView reloadData];
    [self.petPhotoCollectionView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Collection View data Source
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.pet.petImgList.count > 0) {
        if (self.pet.petImgList.count < 3) {
            return self.pet.petImgList.count;
        }else{
            return 3;
        }
    }else{
        return 0;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPPetPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"petPhotoCell" forIndexPath:indexPath];
    PPPetPhoto *photo = [self.pet.petImgList objectAtIndex:indexPath.row];
    [cell.photoView setImageWithURL:[PPImageUrl getImageUrl:photo.img] placeholderImage:[UIImage imageNamed:@"defaultImage"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [cell.photoView setContentMode:UIViewContentModeScaleAspectFill];
    [cell.photoView setClipsToBounds:YES];
    return cell;
}


#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 88;
    }else if (indexPath.row == 5 && indexPath.section == 1){
        return self.photoCellHeight;
    }else if (indexPath.row == 6 && indexPath.section == 1){
        return self.introductionHeight;
    }else {
        return 44;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 5 && indexPath.section == 1){
        PPPreviewPetPhotoViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPPreviewPetPhotoViewController"];
        targetVC.pet = self.pet;
        [self.navigationController pushViewController:targetVC animated:YES];
    }
}

#pragma mark - IBAction

- (IBAction)goEdit:(UIBarButtonItem *)sender {
    if ([sender.title isEqualToString:@"编辑"]) {
        PPEditPetInfoTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPEditPetInfoTableViewController"];
        targetVC.pet = self.pet;
        [self.navigationController pushViewController:targetVC animated:YES];
    }
    
}

- (IBAction)deletePet:(id)sender {
    [UIAlertView showWithTitle:@"放生" message:@"确定要放了它么？" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            [self deleteThePet:self.pet];
        }
    }];
}

- (void)deleteThePet:(PPPetInfo *)pet
{
    NSString *url = [PPAPIList getAPIList].PPDeletePetById;
    NSDictionary *params =@{@"userId":@(pet.userId),
                            @"petId":@(pet.id),
                            };
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSLog(@"%@",responseObject);
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            [UIAlertView showWithTitle:@"再见了" message:@"成功放归大自然！" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                [[PPSystemConfiguraton sharedSystemConfiguration] getPetListwithComepletion:^{
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }];
        } else {
            [UIAlertView showWithTitle:@"宠物不想走" message:@"放归大自然失败，请稍后再试" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        [UIAlertView showWithTitle:@"提示" message:@"网络不给力" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
    }];
}





@end
